package com.xrui.hbaseview.converters;

import com.xrui.hbaseview.format.DateUtils;
import org.apache.hadoop.hbase.util.Bytes;

import java.util.Date;

/**
 * This class is responsible for converting data from byte[] to Date represented as Long and vice versa.
 */
public class DateAsLongConverter extends TypeConverter {

    private static final long serialVersionUID = 7524770450006316409L;

    @Override
    public String toString(byte[] value) {
        if (value == null) {
            return null;
        }
        return DateUtils.format(new Date(Bytes.toLong(value)));
    }

    @Override
    public boolean canConvert(byte[] value) {
        try {
            Bytes.toLong(value);
            return true;
        } catch (Exception ignore) {
            return false;
        }
    }

    @Override
    public boolean supportsFormatting() {
        return false;
    }

    @Override
    public byte[] toBytes(String value) {
        if (value == null) {
            return EMPTY_BYTES_ARRAY;
        }

        Date date = DateUtils.parse(value);
        if (date != null) {
            return Bytes.toBytes(date.getTime());
        }
        return EMPTY_BYTES_ARRAY;
    }
}
